default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from myblog.models import DolphinTestPublicInterface, DolphinTestHeards
from myblog.dolphinService.baseCode import getResonCode
from django.core import serializers
import re
import logging
import math

logger = logging.getLogger('log')
from django.db.models import Q, F


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addPublicInterface(request):  # 新增公共接口接口管理
    data = json.loads(request.body)
    try:
        mmhpubIn = DolphinTestPublicInterface.objects.create(url=data['url'], method=data['method'],
                                                             request_data_type=data['request_data_type'],
                                                             request_header_param=data['request_header_param'],
                                                             request_data_content=data['request_data_content'],
                                                             request_value=data['request_value'])

        mmhherad = DolphinTestHeards.objects.create(headrsName=data["headrsName"], tpi_id=mmhpubIn.request_id)
        mmhherad.save()
        mmhpubIn.save()
        response = getResonCode().getSuccess()
        return JsonResponse(response)

    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


path = "dolphinTestCaseActionSQL.xml"
@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def queryPublicInterface(request):  # 查询公共接口接口管理
    try:
        from myblog.dolphinJOB.dolphinJboContentSqlXML import get_sql
        from myblog.dolphinDabases import connectionDB
        sql = get_sql("Case", "pubInter", "queryPubInter", sqlname=path, fileName="dolphinInterfaceManagementList")
        mmhpubInList = connectionDB.getmoreSql(sql)
        response = getResonCode().getSuccess()
        response["data"] = mmhpubInList
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def runNerPublicInterface(request):  # 运行公共接口接口管理
    data = json.loads(request.body)
    try:

        from myblog.dolphinService.dolphinJOBService.dolphinImplementCase import ExecutionCase
        ExecutionCase().runRepositoryPublicMethod(id=data["id"])
        response = getResonCode().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def delPublicInterface(request):  # 删除共接口接口管理
    data = json.loads(request.body)
    try:
        DolphinTestPublicInterface.objects.get(request_id=data["id"]).delete()
        DolphinTestHeards.objects.get(tpi_id=data["id"]).delete()
        response = getResonCode().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
